#include "TransformComponent.h"

void TransformComponent::_update()
{
	_clear();

	*mPos = mSceneNode->getPosition();
	*mScale = mSceneNode->getScale();
	*mOrient = mSceneNode->getOrientation();
	
	_reconnect();
}

void TransformComponent::_reconnect()
{
	posCon = mPos->onChanged.connect( sigc::mem_fun(this, &TransformComponent::setPosition) );
	rotCon = mOrient->onChanged.connect( sigc::mem_fun(this, &TransformComponent::setOrientation) );
	scaleCon = mScale->onChanged.connect( sigc::mem_fun(this, &TransformComponent::setScale) );
}

void TransformComponent::_clear()
{
	posCon.disconnect();
	rotCon.disconnect();
	scaleCon.disconnect();
}

void TransformComponent::init()
{
	mGo = dynamic_cast<GameObject*>(mContainer);
	assert(mGo);

	SceneManager* sm = Ogre::Root::getSingleton().getSceneManagerIterator().getNext();
	
	mPos = new Property<Vector3>("pos");
	posCon = mPos->onChanged.connect( sigc::mem_fun(this, &TransformComponent::setPosition) );

	mScale = new Property<Vector3>("scale");
	scaleCon = mScale->onChanged.connect( sigc::mem_fun(this, &TransformComponent::setScale) );

	mOrient = new Property<Quaternion>("orientation");
	rotCon = mOrient->onChanged.connect( sigc::mem_fun(this, &TransformComponent::setOrientation) );
	
	// dont create one if we got a manually created scenenode...
	if(mSceneNode==NULL)
		mSceneNode = sm->getRootSceneNode()->createChildSceneNode(mGo->getName()+"_SceneNode");
	else
		_update();
	
	// store the scenenode pointer as a property, other components will probably want to use it...
	mGo->addProperty<SceneNode*>("scenenode", mSceneNode);

	// add properties to a transform object
	mTrans = new Object("transform");
	mTrans->addProperty(dynamic_cast<IProperty*>(mPos));
	mTrans->addProperty(dynamic_cast<IProperty*>(mScale));
	mTrans->addProperty(dynamic_cast<IProperty*>(mOrient));

	mGo->addProperty<Object>("transform", *mTrans);
}
